package com.yiren.dbaa.util;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.telephony.cdma.CdmaCellLocation;
import android.telephony.gsm.GsmCellLocation;
import android.util.Log;

import com.yiren.backstage.currency.bean.GpsInfoBean;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.utils.StringUtil;
import com.yiren.dbaa.global.GlobalApplication;

import org.apache.commons.lang.StringUtils;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Describe 获取基站信息、网速工具类
 *
 * @author WRX
 * @date 2022/12/15
 */
public class BaseSignalUtil {

    private Activity activity;
    private Handler mHandler;
    private TelephonyManager mTelephonyManager;
    private MyPhoneStateListener listener;

    private long lastTotalRxBytes = 0;
    private long lastTimeStamp = 0;
    /*** 是否获取到了SIM卡网络信号强度 */
    private boolean getSimSignalStrength = false;

    public BaseSignalUtil(Activity activity, Handler mHandler) {
        this.activity = activity;
        this.mHandler = mHandler;
        mTelephonyManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        listener = new MyPhoneStateListener();
    }

    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            showNetSpeed();
            getMobileNetworkSignal();
            getStationLocation();
        }
    };

    public void startTask() {
        lastTotalRxBytes = getTotalRxBytes();
        lastTimeStamp = System.currentTimeMillis();
        new Timer().schedule(task, 1000, 1000);  // 1s后启动任务，每1s执行一次
    }

    private long getTotalRxBytes() {
        return TrafficStats.getUidRxBytes(activity.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);//转为KB
    }

    private void showNetSpeed() {
        long nowTotalRxBytes = getTotalRxBytes();
        long nowTimeStamp = System.currentTimeMillis();
        long speed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp)); //毫秒转换
        long speed2 = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 % (nowTimeStamp - lastTimeStamp));//毫秒转换

        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;

        Message msg = mHandler.obtainMessage();
        msg.what = 100;
        msg.obj = String.valueOf(speed) + "." + String.valueOf(speed2) + " kb/s";
        mHandler.sendMessage(msg);//更新界面
    }

    public void cancelTask() {
        if (null != task) {
            task.cancel();
            task = null;
        }
        if (null != mTelephonyManager) {
            mTelephonyManager.listen(listener, PhoneStateListener.LISTEN_NONE);
        }
    }

    /**
     * 获取信号强度
     */
    private void getMobileNetworkSignal() {
        Message msg = mHandler.obtainMessage();
        msg.what = 200;
        if (!hasSimCard(activity)) {
            if (NetWorkUtil.isNetworkAvailable(activity)) {
                msg.obj = obtainWifiInfo();
            } else {
                msg.obj = 0;
            }
            mHandler.sendMessage(msg);
        } else {
            if (!getSimSignalStrength) {
                if (mTelephonyManager != null) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            mTelephonyManager.listen(listener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
                            Looper.loop();
                        }
                    }).start();
                } else {
                    msg.obj = 0;
                    mHandler.sendMessage(msg);
                }
            }
        }
    }

    /**
     * 判断是否包含SIM卡
     *
     * @return 状态
     */
    private boolean hasSimCard(Context context) {
        TelephonyManager telMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        boolean result = true;
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false;  // 没有SIM卡
                break;
        }
        return result;
    }

    /**
     * 获取wifi信号强度
     *
     * @return
     */
    public int obtainWifiInfo() {
        // Wifi的连接速度及信号强度：
        int strength = 0;
        WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (info.getBSSID() != null) {
            return info.getRssi();
            // 链接信号强度，5为获取的信号强度值在5以内
//            strength = WifiManager.calculateSignalLevel(info.getRssi(), 5);
//            // 链接速度
//            int speed = info.getLinkSpeed();
//            // 链接速度单位
//            String units = WifiInfo.LINK_SPEED_UNITS;
//            // Wifi源名称
//            String ssid = info.getSSID();
        }
//        return info.toString();
        return strength;
    }

    /**
     * 获取基站经纬高和卫星数
     */
    private void getStationLocation() {
        int satelliteNum = 0;
        double longitude = 0;
        double latitude = 0;
        double altitude = 0;
        if (StringUtils.isNotEmpty(SignalGConstant.gpsGpgga)) {
            String[] source = SignalGConstant.gpsGpgga.split(",");
            if (null != source && source.length >= 12) {
                satelliteNum = StringUtil.isNothing(source[7]) ? 0 : Double.valueOf(source[7]).intValue();
                longitude = StringUtil.isNothing(source[4]) ? 0 : Double.valueOf(source[4]) / 100d;
                latitude = StringUtil.isNothing(source[2]) ? 0 : Double.valueOf(source[2]) / 100d;
                altitude = StringUtil.isNothing(source[9]) ? 0 : Double.valueOf(source[9]);
            }
        }
        Message msg = mHandler.obtainMessage();
        msg.what = 300;
        msg.obj = satelliteNum + ":" + longitude + ":" + latitude + ":" + altitude;
        mHandler.sendMessage(msg);
    }

    public class MyPhoneStateListener extends PhoneStateListener {

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            getSimSignalStrength = true;
            int asu = signalStrength.getGsmSignalStrength();
            int lastSignal = -113 + 2 * asu;
            Message msg = mHandler.obtainMessage();
            msg.what = 200;
            if (lastSignal > 0) {
                msg.obj = lastSignal;
            } else {
                msg.obj = 0;
            }
            mHandler.sendMessage(msg);
//            Looper.myLooper().quit();
        }
    }

}